#!/bin/bash

set -eo pipefail

RN_VERSION=$1
DESTINATION=$(dirname $2)
PROJECT_NAME=$(basename $2)

function get-flow-version {
  cat .flowconfig| grep -A 1 '\[version\]' | tail -1
}

function generate-project {
  react-native init --version="$RN_VERSION" $PROJECT_NAME

  pushd $PROJECT_NAME
    FLOW_VERSION=$(get-flow-version)
    yarn add flow-bin@$FLOW_VERSION --dev
    # install react-native-ble-plx using the github commit
    CURRENT_COMMIT=${TRAVIS_PULL_REQUEST_SHA:-$TRAVIS_COMMIT}
    echo "Installing react-native-ble-plx revision $CURRENT_COMMIT"
    # Using npm here to be able to download submodules properly.
    npm install --save https://github.com/Polidea/react-native-ble-plx#$CURRENT_COMMIT
    # Sometimes yarn doesn't install packets locally. Be sure that everything is in place.
    npm install
    react-native link react-native-ble-plx  # and link it
    rm -rf ../../node_modules
  popd
}

function patch-project {
  for filename in patches/common/*.patch; do
    [ -e "$filename" ] || continue
    echo "Applying common patch - $filename"
    git apply "$filename" || echo Patch not applied.
  done

  for filename in patches/rn-$RN_VERSION/*.patch; do
    [ -e "$filename" ] || continue
    echo "Applying patch specifically for $RN_VERSION - $filename"
    git apply "$filename" || echo Patch not applied.
  done
}

function add-test-suite {
  cp scripts/test-utils/{App.js,TestCase.js,TestSuite.js,utils.js} $PROJECT_NAME
}

function add-espresso {
  cp -r scripts/test-utils/androidTest $PROJECT_NAME/android/app/src/
}

function add-earl-grey {
  PROJECT_PATH="$PROJECT_NAME/ios/"
  cp scripts/test-utils/SetupTests.m $PROJECT_PATH/SetupTests/SetupTests.m
}

function update-pods {
  PROJECT_PATH="$PROJECT_NAME/ios/"
  if [ -f "$PROJECT_PATH/Podfile" ]; then
    echo 'Updating Podfile dependencies...'
    pushd $PROJECT_PATH
      pod update
    popd
  fi
}

function apply-before-scripts {
  if [ "system-$TRAVIS_OS_NAME" == "system-osx" ]; then
    BEFORE_SCRIPT_PATH=patches/rn-$RN_VERSION/*.ios.sh
  else
    BEFORE_SCRIPT_PATH=patches/rn-$RN_VERSION/*.android.sh
  fi

  for filename in $BEFORE_SCRIPT_PATH; do
    [ -e "$filename" ] || continue
    echo "Executing $filename..."
    $filename $PROJECT_NAME
  done
}

pushd $DESTINATION
  generate-project
  patch-project
  scripts/enable-swift $PROJECT_NAME
  add-test-suite

  if [ "system-$TRAVIS_OS_NAME" == "system-osx" ]; then
    add-earl-grey
    update-pods
  else
    add-espresso
  fi

  apply-before-scripts
popd
